export const trim = str => {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

export const formatUrl = (path, option) => {
  let query = [];
  if (Object.prototype.toString.call(option) === '[object Object]'){
    for(let p in option){
      query.push(p + '=' + option[p]);
    }
  }

  if (query.length){
    return path + (path.indexOf('?') === -1 ? '?' : '&') + query.join('&');
  }
  else{
    return path;
  }
}

export const getWordLen = (str) => {
  str += '';

  let realLength = 0, charCode = -1;

  for(let codePoin of str){
    charCode = codePoin.charCodeAt(0);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    }
    else {
      realLength += 2;
    }
  }

  return realLength;
}

export const goTo = (option = {}, redirect) => {
  const app = getApp();
  let { url, appId, path } = option;
  let current;

  // 跳转小程序
  if (appId && path) {
    // 跳转站外小程序
    if (appId !== app.appId) {
      wx.navigateToMiniProgram(option);
      return;
    } else {
      url = path;
    }
  }

  if(!url){
    return;
  }

  url = trim(url);

  const { tabBar = {} } = __wxConfig;
  const { list = [] } = tabBar;

  if(!url.startsWith('/')){
    url = '/' + url;
  }

  const swith = list.find(item => {
    return url.startsWith('/' + item.pagePath);
  });

  if (swith) {
    wx.switchTab(Object.assign({}, option));
    // switchTab不支持queryString，后面要做个兼容
    return;
  }

  if (redirect){
    wx.redirectTo(Object.assign({}, option));
    return;
  }

  const pages = getCurrentPages();
  let len = pages.length - 1;
  let idx = len;

  for(;idx >= 0; idx--){
    const item = pages[idx];
    if (url.indexOf(item.route) !== -1) {
      current = item;
      break;
    }
  }

  const delta = len - idx;


  if(delta === 0){ // 跳当前页
    wx.redirectTo(option);
  }
  else if (delta <= len) {// 后退
    if(current){
      const search = url.split('?');
      if(search.length > 1){
        current.params = decodeSearch(null, '?' + search[1]);
      }
    }
    wx.navigateBack(Object.assign(option, {
      delta
    }));
  }
  else { // 新页面
    wx.navigateTo(option);
  }
}

export const getStyle = (option = {}) => {
  if(!option){
    return '';
  }

  let style = [];
  for(let p in option){
    style.push(p + ':' + option[p]);
  }
  return style.join(';');
}

export const addZero = (num) => {
  return ("00" + num).substr(("" + num).length);
}

export const getMenuInfo = () => {
  const app = getApp();
  
  if (app.menuInfo) {
    return app.menuInfo;
  }

  const menu = wx.getMenuButtonBoundingClientRect();
  const sys = wx.getWindowInfo();
  const scale = sys.windowWidth / 375;

  app.menuInfo = {
    bottom: menu.bottom * 2 / scale,
    height: menu.height * 2 / scale,
    left: menu.left * 2 / scale,
    right: menu.right * 2 / scale,
    top: menu.top * 2 / scale,
    width: menu.width * 2 / scale,
    absRight: (sys.windowWidth - menu.right) * 2 / scale,
    absBottom: (sys.windowHeight - menu.bottom) * 2 / scale,
  };
  return app.menuInfo;
}

export const camelCase = (string) => {
  return string ? string.replace(/-\D/g, function (match) {
      return match.charAt(1).toUpperCase();
  }) : '';
}

export const hyphenate = (string) => {
  return string ? string.replace(/[A-Z]/g, function (match) {
      return ('-' + match.charAt(0).toLowerCase());
  }) : '';
}

export const setTimeToast = (page, title='', second=0, icon='', callback) => {
  if(second > 0){
    page.setData({
      toast: {
        show: true,
        title,
        remain: second--,
        icon
      }
    });

    let toastTimeId = setInterval(() => {
      if(second < 0){
        page.setData({
          toast: {
            show: false
          }
        });
        clearInterval(toastTimeId);
        if(typeof callback === 'function'){
          callback();
        }
      }
      else{
        page.setData({
          toast: {
            show: true,
            title,
            remain: second--,
            icon
          }
        });
      }
    }, 1000);
  }
}

export const toLocaleString = (num) => {
  if(Number.isNaN(num)){
    return num;
  }

  const all = ('' + num).split('.');
  const integer = all[0];
  const decimal = all[1];
  let str = '';

  if(integer){
    const nums = integer.split('');

    for(let i = nums.length - 3; i > 0; i -=3 ){
      nums.splice(i,0,',');
    }

    str += nums.join('');
  }

  if(decimal){
    const nums = decimal.split('');
    let len = nums.length;
    for(let i = 3; i < len; i +=3 ){
      nums.splice(i,0,',');
      len += 1;
      i += 1;
    }

    str += '.' + nums.join('');
  }


  return str;
}

export const decodeSearch = (obj, search) => {
  var newObj = {},
      match;

  if(obj){
      if(typeof obj === 'string'){
          newObj = decodeSearch(null, obj);
      }
      else{
          search = decodeURIComponent(search);
          for(var p in obj){
              match = search.match(new RegExp('[?&]' + p + '=([^&]*)'));
              newObj[p] = match ? match[1] : obj[p];
          }
      }
  }
  else{
      search = decodeURIComponent(search);
      search.replace(new RegExp('[?&]([\\S]+)*?[^&]*', 'g'), function(expression){
          var exp = expression.replace(/^\s+|\s+$/g, '').slice(1),
              exps;
          if(exp){
              exps = exp.split('=');
              if(exps){
                  newObj[exps[0]] = exps[1] || '';
              }
          }
      });
  }

  return newObj;
};

export const updateScrollHeight = (cls) => {
  const app = getApp();

  wx.nextTick(() => {
    wx.createSelectorQuery().select(cls || '.main-page').boundingClientRect(rect => {
      if(rect){
        app.page.setData({
          scrollHeight: rect.height
        })
      }
    }).exec();
  });
}

export const getLocation = () => {
  const app = getApp();

  return new Promise((resolve, reject) => {
    const location = wx.getStorageSync(app.envPrefix + '-location');
    let time;

    if(location && location.time){
      time = new Date(location.time);
    }
    if(time && (new Date().getTime() - time.getTime() < 600000)){ // 十分钟之内
      resolve(location.data);
    }
    else{
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          wx.setStorageSync(app.envPrefix + '-location', {
            time: dateToStr(new Date(), 'yyyy/MM/dd hh:mm:ss'),
            data: res
          });
          resolve(res);
        },
        fail: err => {
          reject(err);
        }
      })
    }
  })
}

export const uploadFile = (filePath) => {
  const app = getApp();
  const { appId, root } = app.$app;

  return new Promise((resolve, reject) => {
    const headers = {
      "weapp-appid": appId,
      "weapp-env": __wxConfig.envVersion,
    };

    const jwt = wx.getStorageSync("KEY_JWT");
    if (jwt) {
      headers.Authorization = `Bearer ${jwt}`;
    }

    wx.uploadFile({
      url: `${root}/upload/local-save`,
      filePath: filePath,
      name: "file",
      header: headers,
      formData: {
        openId: wx.getStorageSync("openId"),
        unionId: wx.getStorageSync("unionId"),
      },
      success: function (res) {
        console.log("login.uploadFile", res);
        resolve(JSON.parse(res.data));
      },
      fail: function (e) {
        reject(e);
      },
    });
  });
};

export const uploadImg = (count=9, sourceType=['album', 'camera']) => {
  const app = getApp();
  const { appId, root } = app.$app;

  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count,
      sizeType: ['compressed'],
      // sourceType,
      success: (res) => {
        console.log(res);
        const files = res.tempFiles.map(item => item.path);
        const all = files.every(file => /\.(jpg|png|jpeg)$/i.test(file));

        if(!all) {
          wx.showToast({
            title: '请上传正确的图片格式！',
            icon: 'none'
          });
        }

        wx.showLoading({
          icon: 'none',
          title: '上传中...',
        });

        const headers = {
          "weapp-appid": appId,
          "weapp-env": __wxConfig.envVersion,
        };

        const jwt = wx.getStorageSync("KEY_JWT");
        if (jwt) {
          headers.Authorization = `Bearer ${jwt}`;
        }

        let index = 0;
        const newFiles = [];

        files.forEach(file => {
          wx.uploadFile({
            url: `${root}/upload/local-save`,
            filePath: file,
            name: "file",
            header: headers,
            formData: {
              openId: wx.getStorageSync("openId"),
              unionId: wx.getStorageSync("unionId"),
            },
            success: function (res) {
              const data = JSON.parse(res.data);
              const filePath = data.url
              newFiles.push(filePath);
            },
            fail: function (e) {
              console.log(file + '上传失败');
              reject(e);
            },
            complete: res => {
              if(++index === files.length){
                wx.hideLoading();
                resolve(newFiles);
              }
            }
          });
        });
      }
    })
  })
};
